package com.onlinelearn.courseservice.service;

import com.onlinelearn.courseservice.repository.CourseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CourseEnrollmentService {
    @Autowired
    private CourseRepository courseRepository;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private NotificationTriggerService notificationService;

    public CourseEnrollmentResult enrollCourse(Long studentId, Long courseId) {
        Course course = courseRepository.findById(courseId)
            .orElseThrow(() -> new CourseNotFoundException(courseId));

        // 检查课程是否可选
        if (course.getStatus() != CourseStatus.PUBLISHED) {
            throw new CourseNotAvailableException("课程未发布");
        }

        // 检查是否为付费课程
        if (course.getPrice() > 0) {
            PaymentResult paymentResult = paymentService.processPayment(studentId, courseId);
            
            if (!paymentResult.isSuccess()) {
                return CourseEnrollmentResult.paymentFailed(paymentResult.getErrorMessage());
            }
        }

        // 添加学生到课程
        course.enrollStudent(studentId);
        courseRepository.save(course);

        // 发送选课通知
        notificationService.triggerCourseEnrollmentNotification(studentId, courseId);

        return CourseEnrollmentResult.success(course);
    }

    public List<Course> getStudentCourses(Long studentId, CourseFilter filter) {
        return courseRepository.findByStudentIdAndFilter(studentId, filter);
    }
}

// 课程过滤器
class CourseFilter {
    private CourseCategory category;
    private CourseStatus status;
    // Getter和Setter
} 